var WxParse = require('../../wxParse/wxParse.js');
const app = getApp();

Page({
  data: {
    id: 0,
    goods_detail: {},

    receiver: '',  // 收货人
    tel: '',  // 电话
    address: '',  // 地址
    purchase_loading: false
  },
  onLoad(options) {
    this.data.id = parseInt(options.id);
    this.goodsDetail();
    this.addressList();
  },
  // 商品详情
  goodsDetail() {
    app.ajax('shop/goodsDetail', { id: this.data.id }, res => {
      this.setData({ goods_detail: res });
      wx.setNavigationBarTitle({ title: res.name });
    });
  },
  // 获取默认收货地址
  addressList() {
    let post = {
      token: app.user_data.token
    };

    app.ajax('my/getDefaultAddress', post, (res) => {
      if (res) {
        this.setData({
          receiver: res.username,
          tel: res.tel,
          address: res.provincename + ' ' + res.cityname + ' ' + res.countyname + ' ' + res.detail
        });
      }
    });
  },
  // 选择收货地址，在其他页调用
  choose_address(receiver, tel, address, callback) {
    this.setData({
      receiver: receiver,
      tel: tel,
      address: address
    }, () => {
      if (callback) {
        callback();
      }
    });
  },
  // 下单
  purchase() {
    if (!this.data.purchase_loading) {
      let data = this.data;
      if (!data.address.trim()) {
        app.toast('请填写收货地址');
      } else {
        this.setData({ purchase_loading: true });

        let post = {
          token: app.user_data.token,
          goods_id: this.data.id,
          num: 1,
          receiver: this.data.receiver,
          tel: this.data.tel,
          address: this.data.address
        };

        app.ajax('shop/purchase', post, (pay_order_sn) => {
          this.orderPay(pay_order_sn, (res) => {
            if (res) {
              wx.redirectTo({ url: '/pages/my-orders/my-orders?status=1' });
            } else {
              app.modal('支付未完成，可以在我的订单中进行后续的付款操作', () => {
                wx.redirectTo({ url: '/pages/my-orders/my-orders?status=0' });
              })
            }
          });
        }, null, () => {
          this.setData({ purchase_loading: false });
        });
      }
    }
  },
  // 支付
  orderPay(pay_order_sn, complete) {
    let post = {
      token: app.user_data.token,
      pay_order_sn: pay_order_sn
    };

    app.ajax('pay/orderPay', post, (res) => {
      wx.requestPayment({
        timeStamp: res.timeStamp,
        nonceStr: res.nonceStr,
        package: res.package,
        signType: 'MD5',
        paySign: res.paySign,
        success() {
          complete(true);
        },
        fail() {
          app.toast('支付失败');
          complete(false);
        }
      })
    });
  }
});